package com.tomato.lock.util;

import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 * 自定义线程工程,如果自定义线程池执行任务出错，可以方便排查
 * </p>
 */
public class TomatoThreadFactory implements ThreadFactory {

    public final ThreadGroup group;

    public final String prefix;

    public final AtomicInteger integer = new AtomicInteger(1);

    public TomatoThreadFactory() {
        this("");
    }

    public TomatoThreadFactory(String prefixName) {
        SecurityManager securityManager = System.getSecurityManager();
        group = securityManager == null ? Thread.currentThread().getThreadGroup() : securityManager.getThreadGroup();
        prefix = StringUtils.isBlank(prefixName) ? "tomato-thread-pool" : prefixName;
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(group, r, prefix + "-" + integer.getAndIncrement(), 0);

        if (thread.isDaemon()) {
            thread.setDaemon(false);
        }

        if (thread.getPriority() != Thread.NORM_PRIORITY) {
            thread.setPriority(Thread.NORM_PRIORITY);
        }
        return thread;
    }
}
